import { costStatisticsListApi, exportCostStatisticsApi } from '@/api/pcs/pcsCostStatistics'
import { defaultPageSize } from '@/utils/antdHelper'
import { formatDate } from '@/utils/displayHelper'
import { exportFile } from '@/utils/downloadFile'
import modelExtend from '@/utils/dvaUtil/modelExtend'

export const namespace = 'pcsCostStatistics'

const initialState = {
  searchParams: {},
  pagination: {
    current: 1,
    pageSize: defaultPageSize,
    total: 0,
  },
  pageList: [],
  totalObj: {
    totalBillAmount: 0, //合计账单费用
    totalPayAmount: 0, //合计支付金额
    totalPayCommission: 0, //合计支付手续费
    totalNursingAmount: 0, //合计护工费用
    totalServiceCharge: 0, //合计应缴服务费
    totalManageFee: 0, //合计管理费用
  },
}

export default modelExtend({
  namespace,
  state: initialState,
  matchedActions: toAction => {
    toAction('getPageList')
  },
  effects: {
    *getPageList({ payload }, { call, update, select }) {
      const { searchParams, pagination } = yield select(state => state[namespace])
      const params = {
        ...searchParams,
        ...pagination,
        ...payload,
      }

      if (params.payDateRange?.length) {
        params.payStartDate = formatDate(params.payDateRange[0])
        params.payEndDate = formatDate(params.payDateRange[1])
        delete params.payDateRange
      }
      if (params.areaIdList?.length) {
        params.areaId = params.areaIdList[1]
        delete params.areaIdList
      }

      const { data } = yield call(costStatisticsListApi, params)
      const {
        content,
        current,
        pageSize,
        total,
        totalBillAmount,
        totalPayAmount,
        totalPayCommission,
        totalNursingAmount,
        totalServiceCharge,
        totalManageFee,
      } = data
      yield update({
        pageList: content,
        pagination: { current, pageSize, total },
        totalObj: {
          totalBillAmount,
          totalPayAmount,
          totalPayCommission,
          totalNursingAmount,
          totalServiceCharge,
          totalManageFee,
        },
      })
    },
    *exportFile(_, { select }) {
      const { searchParams, pagination } = yield select(state => state[namespace])
      const params = {
        ...searchParams,
        ...pagination,
      }

      if (params.payDateRange?.length) {
        params.payStartDate = formatDate(params.payDateRange[0])
        params.payEndDate = formatDate(params.payDateRange[1])
        delete params.payDateRange
      }
      if (params.areaIdList?.length) {
        params.areaId = params.areaIdList[1]
        delete params.areaIdList
      }
      yield exportFile({
        api: exportCostStatisticsApi,
        params,
      })
    },
  },
})
